//
//  registerViewController.m
//  Router
//
//  Created by teki on 15/10/13.
//  Copyright © 2015年 dc. All rights reserved.
//

#import "RegisterViewController.h"
#import "CustomTextField.h"
#import "UserHelper.h"
#import "UserSingleton.h"
#import "BindWIFIListViewController.h"
#import "AppDelegate.h"
#import "LoginResponseModel.h"

@interface RegisterViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) UIScrollView *rootScrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) CustomTextField *phoneTextField;
@property (nonatomic, strong) CustomTextField *passwordTextField;

@property (nonatomic, strong) UIButton *agreeButton;

@property (nonatomic, strong) UserHelper *userHelper;
@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.userHelper = [[UserHelper alloc] init];
    
    
    self.navigationItem.title = @"用户注册";
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self initContentView];

    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)initContentView
{
    
    //内容跟视图
    _rootScrollView=[[UIScrollView alloc]init];
    _rootScrollView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_rootScrollView];
    [_rootScrollView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureClick:)];
    [_rootScrollView addGestureRecognizer:tapGesture];
    //内容视图
    _contentView = UIView.new;
    _contentView.backgroundColor = [UIColor clearColor];
    [_rootScrollView addSubview:_contentView];
    [_contentView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_rootScrollView);
        make.width.equalTo(_rootScrollView);
    }];
    
    
    
    UIFont *labelFont = [UIFont systemFontOfSize:15.0f];
    UIColor*textColor = SeparatorLineColor;
    UIColor *borderColor = [UIColor colorWithHexString:@"c3c3c3"];
    int fontSize = 14.0f;

    CGFloat leadingPadding = 28;
    CGFloat labelPadding = 5;
    CGFloat textFieldPadding = 22;
    CGFloat textFieldHeight = 35.0f;
    
    UILabel *moble = [_contentView addLabelWithText:@"用户名" font:labelFont color:textColor];
    
    _phoneTextField = [[CustomTextField alloc]initWithType:CustomTextFieldTypeNone target:self FontSize:fontSize];
    _phoneTextField.textField.keyboardType = UIKeyboardTypeEmailAddress;
    [_phoneTextField setStyleColor:borderColor];
    _phoneTextField.textField.textColor = [UIColor blackColor];
    _phoneTextField.placeholder = @"请输入11位手机号码";
    _phoneTextField.textField.returnKeyType = UIReturnKeyNext;
    [_contentView addSubview:_phoneTextField];
    
    [moble makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leadingPadding);
        make.top.equalTo(32);
        make.width.equalTo(50);
        
    }];
    
    [_phoneTextField makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(25);
        make.left.equalTo(moble.right).offset(labelPadding);
        make.right.equalTo(_contentView.right).offset(-leadingPadding);
        make.height.equalTo(textFieldHeight);
    }];
    

    
    UILabel *passwordLabel = [_contentView addLabelWithText:@"密    码" font:labelFont color:textColor];
    
    _passwordTextField = [[CustomTextField alloc]initWithType:CustomTextFieldTypeNone target:self FontSize:fontSize];
    [_passwordTextField setStyleColor:borderColor];
    _passwordTextField.textField.secureTextEntry = YES;
    _passwordTextField.textField.textColor = [UIColor blackColor];
    _passwordTextField.placeholder = @"请输入密码";
    _passwordTextField.isShowPasswordButton = YES;
    _passwordTextField.textField.textColor = [UIColor blackColor];
    _passwordTextField.textField.returnKeyType = UIReturnKeyDone;
    [_contentView addSubview:_passwordTextField];
    
    [_passwordTextField makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_phoneTextField.bottom).offset(textFieldPadding);
        make.left.equalTo(passwordLabel.right).offset(labelPadding);
        make.right.equalTo(_contentView.right).offset(-leadingPadding);
        make.height.equalTo(textFieldHeight);
    }];

    
    [passwordLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leadingPadding);
        make.top.equalTo(moble.bottom).offset(40);
        make.width.equalTo(50);
    }];
    

    UIButton *registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    registerButton.translatesAutoresizingMaskIntoConstraints = NO;
    registerButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [registerButton setTitle:@"注  册" forState:UIControlStateNormal];
    registerButton.layer.cornerRadius = 5.0f;
    registerButton.layer.masksToBounds = YES;
    [registerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [registerButton setBackgroundImage:[UIImage imageWithColor:NavgationBarBackgroundColor] forState:UIControlStateNormal];
    [registerButton setBackgroundImage:[UIImage imageWithColor:RGB(78, 148, 70)] forState:UIControlStateSelected];
    [registerButton addTarget:self action:@selector(registerButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:registerButton];
    [registerButton makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_passwordTextField.bottom).offset(textFieldPadding);
        make.left.equalTo(leadingPadding);
        make.right.equalTo(-leadingPadding);
        make.height.equalTo(45);
    }];
    
    
    _agreeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _agreeButton.translatesAutoresizingMaskIntoConstraints = NO;
    UIImage *normalImage = [UIImage imageNamed:@"register_agreen_non"];
    UIImage *selectImage = [UIImage imageNamed:@"register_agreen"];
    [_agreeButton setImage:normalImage forState:UIControlStateNormal];
    [_agreeButton setImage:selectImage  forState:UIControlStateSelected];
    [_agreeButton addTarget:self action:@selector(agreeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:_agreeButton];
    [_agreeButton makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(30);
        make.top.equalTo(registerButton.bottom).offset(30);
        make.size.equalTo(normalImage.size);
    }];
    
    UILabel *label = [_contentView addLabelWithText:@"同意  小叶网络使用协议" font:labelFont color:textColor];
    [label makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_agreeButton.right).offset(10);
        make.centerY.equalTo(_agreeButton);
        make.bottom.equalTo(_contentView.bottom).offset(-10);
    }];

}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([textField isEqual:_phoneTextField.textField]) {
        [_passwordTextField.textField becomeFirstResponder];
        return YES;
    }
    else
    {
        [_passwordTextField.textField resignFirstResponder];
        return YES;
    }
}

#pragma mark -
#pragma mark   IBActions
- (void)tapGestureClick:(UITapGestureRecognizer *)guesture
{
    [self resignAllTextFiled];
}


- (void)resignAllTextFiled
{
    [_phoneTextField.textField resignFirstResponder];
    [_passwordTextField.textField resignFirstResponder];
}



- (void)registerButtonPressed:(UIButton *)sender
{
    
    [self resignAllTextFiled];
    NSString *user = _phoneTextField.textField.text;
    NSString *password = _passwordTextField.textField.text;
    if (![user isValidate2])
    {
        [self promptMessage:@"用户名格式不正确!"];
        return;
    }
    
    if ([password checkEmpty]) {
        [self promptMessage:@"密码不能为空!"];
        return;
    }

    if (!self.agreeButton.selected) {
        [self promptMessage:@"请同意小叶网络使用协议"];
        return;
    }
    [self newUserRegisterRequestWith:user password:password];

}



- (void)agreeButtonPressed:(UIButton *)sender
{
    sender.selected = !sender.selected;
}





#pragma mark -
#pragma mark   Requests

- (void)newUserRegisterRequestWith:(NSString *)user
                          password:(NSString *)password
{
    [self.userHelper registerWithPhone:user password:password success:^(BOOL succ, id responseObject, NSString *msg) {
        if (succ)
        {
            [self promptMessage:msg];
            [self dispatchTimerWithTime:2.0 block:^{
                [self.navigationController popViewControllerAnimated:YES];
            }];
//            [self loginRequestWithUser:user andPassword:password];
        }
        else
        {
            [self promptMessage:msg];
        }

    } failure:^(NSError *error) {
        NSString *failedReason = [error localizedDescription];
        [self stopActivityWithActivity:self.activity title:failedReason];
    }];
}


/// 已弃用
- (void)loginRequestWithUser:(NSString *)user
                 andPassword:(NSString *)password
{
    [self.userHelper loginWithPhone:user password:password success:^(BOOL succ, id responseObject, NSString *msg) {
        if (succ) {
            [self stopActivityWithActivity:self.activity title:nil];
            LoginResponseModel *model = (LoginResponseModel *)responseObject;
            UserSingleton *singleton = [UserSingleton shareInstance];
            singleton.userModel = model;
            [singleton saveData];
            
            if ([model.bindDevice count] > 0)
            {
                UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                UIViewController *mainVC = [main instantiateViewControllerWithIdentifier:@"MainVC"];
                ApplicationDelegate.window.rootViewController = mainVC;
            }
            else{
                BindWIFIListViewController *buynowVC = [[BindWIFIListViewController alloc] init];
                BaseNavigationViewController *baseNav = [[BaseNavigationViewController alloc] initWithRootViewController:buynowVC];
                ApplicationDelegate.window.rootViewController = baseNav;
            }
        }
        else{
            [self stopActivityWithActivity:self.activity title:msg];
            //    LoginPromtView *view = [LoginPromtView loadViewFromNib];
            //    [view show];
        }
    } failure:^(NSError *error) {
        NSString *failedReason = [error localizedDescription];
        [self promptMessage:failedReason];

    }];
}



@end
